package org.hfy.exception;

import org.hfy.common.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 全局异常处理器
 * 
 * @author hfy
 * @version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理仓库业务异常
     */
    @ExceptionHandler(WarehouseException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<?> handleWarehouseException(WarehouseException e) {
        logger.error("仓库业务异常: {}", e.getMessage(), e);
        
        // 根据不同类型的仓库异常返回不同的错误码
        if (e instanceof WarehouseException.InsufficientStockException) {
            return ApiResponse.error(4001, e.getMessage());
        } else if (e instanceof WarehouseException.DataNotFoundException) {
            return ApiResponse.error(4004, e.getMessage());
        } else if (e instanceof WarehouseException.InvalidStatusException) {
            return ApiResponse.error(4002, e.getMessage());
        } else if (e instanceof WarehouseException.QuantityValidationException) {
            return ApiResponse.error(4003, e.getMessage());
        } else if (e instanceof WarehouseException.NumberGenerationException) {
            return ApiResponse.error(5001, e.getMessage());
        } else if (e instanceof WarehouseException.ConcurrentOperationException) {
            return ApiResponse.error(4009, e.getMessage());
        }
        
        // 默认仓库异常
        return ApiResponse.error(4000, e.getMessage());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<?> handleBusinessException(BusinessException e) {
        logger.error("业务异常: {}", e.getMessage(), e);
        return ApiResponse.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder("参数校验失败:");
        
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            sb.append(" [").append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append("] ");
        }
        
        logger.error("参数校验异常: {}", sb.toString(), e);
        return ApiResponse.error(400, sb.toString());
    }
    
    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder("参数绑定失败:");
        
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            sb.append(" [").append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append("] ");
        }
        
        logger.error("参数绑定异常: {}", sb.toString(), e);
        return ApiResponse.error(400, sb.toString());
    }
    
    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleConstraintViolationException(ConstraintViolationException e) {
        logger.error("约束违反异常: {}", e.getMessage(), e);
        return ApiResponse.error(400, "参数校验失败: " + e.getMessage());
    }

    /**
     * 处理其他所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<?> handleException(Exception e) {
        logger.error("系统异常: {}", e.getMessage(), e);
        return ApiResponse.error(500, "服务器内部错误: " + e.getMessage());
    }
} 